<?php
namespace App\Http\Utils;

use EasyWeChat\Factory;

class Wechat
{
    /**
     * 新版本code交换手机号
     * @param string $code
     * @param string|null $token
     */
    public static function getPhoneByCode(string $code,?string $token=null){

        if (empty($token)){
            $res=Factory::miniProgram(config('wechat.mini_program.default'))->access_token->getToken();
            $token=$res['access_token']??$token;
        }
        $url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token;
        $res=curl_post($url,['code'=>$code],['Content-type: application/json'],'json');

        if(isset($res['errcode'])&&$res['errcode']==40001){//token失效
            Factory::miniProgram(config('wechat.mini_program.default'))->access_token->getToken(true);
        }
        return $res;
    }

    /**
     * 获取OPENID,员工和商家端目前的机制没法直接用easywechat
     * @param string $code
     */
    public static function getOpenID(string $code){
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".env('WECHAT_OFFICIAL_ID')."&secret=".env('WECHAT_OFFICIAL_SECRET')."&code={$code}&grant_type=authorization_code";

        return curl_get($url);
    }
}
